package mic.hsacnu.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtil {

	public static void requestHttpWithString(String url, boolean isPost, String content, HttpCallback callback){
		if(isPost==false){
			//GET????
			BufferedReader brin=null;
			try {
				URL requestUrl=new URL(url);
				URLConnection httpconn=requestUrl.openConnection();
				httpconn.connect();
				brin=new BufferedReader(new InputStreamReader(httpconn.getInputStream()));
				StringBuilder sb=new StringBuilder();
				String temp;
				while((temp=brin.readLine())!=null){
					sb.append(temp);
				}
				String result=sb.toString();
				callback.onRecived(true, result, null);
			} catch (IOException e) {
				// TODO: handle exception
				callback.onRecived(false, null, e);
			}finally{
				if (brin!=null) {
					try {
						brin.close();
					} catch (IOException e) {
						callback.onRecived(false, null, e);
					}
				}
			}
		}else{
			BufferedReader brin=null;
			PrintWriter pwot=null;
			try {
				URL requestUrl=new URL(url);
				URLConnection httpconn=requestUrl.openConnection();
				httpconn.setDoInput(true);
				httpconn.setDoOutput(true);
				httpconn.connect();
				pwot=new PrintWriter(new OutputStreamWriter(httpconn.getOutputStream()));
				pwot.print(content);
				pwot.flush();
				brin=new BufferedReader(new InputStreamReader(httpconn.getInputStream()));
				StringBuilder sb=new StringBuilder();
				String temp;
				while((temp=brin.readLine())!=null){
					sb.append(temp);
				}
				String result=sb.toString();
				callback.onRecived(true, result, null);
			} catch (IOException e) {
				// TODO: handle exception
				callback.onRecived(false, null, e);
			}finally{
				if (brin!=null) {
					try {
						brin.close();
					} catch (IOException e) {
						callback.onRecived(false, null, e);
					}
				}
				if(pwot!=null){
					pwot.close();
				}
			}
		}
	}
	
	public static void requestHttpWithBytes(){
		
	}
	
	public static void main(String[] args) {
		HttpCallback hcb=new HttpCallback() {
			
			@Override
			public void onRecived(boolean isSucces, String results, Exception e) {
				// TODO Auto-generated method stub
				System.out.println("result: "+isSucces+"\nresults_string: "+results);
			}
		};
		requestHttpWithString("http://www.baidu.com", false, null, hcb);
	}
}
